package band.wukong.practice.webservice.kh.sample08;

import com.sun.xml.ws.api.message.Header;
import com.sun.xml.ws.api.message.HeaderList;
import com.sun.xml.ws.developer.JAXWSProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.ws.WebServiceContext;
import java.util.List;

/**
 * @author wukong(wukonggg@139.com)
 */
@WebService(
    endpointInterface = "band.wukong.practice.webservice.kh.sample08.UserService",
    wsdlLocation = "META-INF/wsdl/kh/sample08-user-wrappered.wsdl",   //独立运行
//    wsdlLocation = "WEB-INF/wsdl/kh/sample08-user.wsdl",                //WEB运行
    targetNamespace = UserConst.SERVICE_NS,
    serviceName = UserConst.SERVICE_NAME,
    portName = UserConst.PORT_NAME
)
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private UserDao userDao = UserDao.newInstance();

    @Resource
    private WebServiceContext context;

    @Override
    public void add(User user) throws UserException {
        verifyLicense();
        userDao.add(user);
    }

    @Override
    public void delete(String name) throws UserException {
        verifyLicense();
        userDao.delete(name);
    }

    @Override
    public List<User> list() {
        return userDao.list();
    }

    @Override
    public User login(String name, String passwd) throws UserException {
        return userDao.login(name, passwd);
    }

    private void verifyLicense() throws UserException {
        // 从消息头中获取相应的信息
        HeaderList headers = (HeaderList) context.getMessageContext().get(JAXWSProperties.INBOUND_HEADER_LIST_PROPERTY);
        if (null == headers)    throw new UserException("该功能需权限控制");
        Header header = headers.get(new QName(UserConst.SERVICE_NS, "licenceInfo"), true);
        if (null == header)    throw new UserException("该功能需权限控制");

        XMLStreamReader reader = null;
        User user = null;
        try {
            reader = header.readHeader();
            user = xml2user(reader);

        } catch (XMLStreamException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);  // 这样写不好。。
        }

        User u = userDao.queryByName(user.getName());
        if (null == u) {
            throw new UserException("没找到授权用户");
        } else if (!u.getPasswd().equals(user.getPasswd())) {
            throw new UserException("授权用户密码不正确");
        }

        logger.debug("user = " + user);
    }

    private User xml2user(XMLStreamReader reader) throws XMLStreamException {
        User user = new User();
        while(reader.hasNext()) {
            int event = reader.next();
            if (event == XMLEvent.START_ELEMENT) {
                String elementName = reader.getName().toString();
                logger.debug("name = " + elementName);
                if ("name".equals(elementName)) {
                    user.setName(reader.getElementText());
                } else if ("passwd".equals(elementName)) {
                    user.setPasswd(reader.getElementText());
                }
            }
        }
        return user;
    }
}
